<template>
  <div>
    <TableSearch
      :search="state.search"
      @search="onSearch"
      @listenClick="listenClick"
    >
      <template v-slot:addPerson>
        <el-button
          type="primary"
          v-loading="uploadLoading"
          @click="addPerson"
          v-if="
            buttonDisplayOrNot(buttonCodes, 'zzAddPersonnelBtn') &&
            bindType != 2
          "
          >新增人员</el-button
        >
      </template>
      <template v-slot:importTemp>
        <el-upload
          v-model:file-list="fileList"
          ref="uploadRef"
          :action="`${proxy.$http}/user/mobile/userInfo/importUser`"
          :auto-upload="true"
          multiple
          :http-request="handleUpload"
          :before-upload="fileBeforeUpload"
          :on-error="fileError"
          :limit="1"
          :show-file-list="false"
          :headers="headers"
          accept=".xls,.xlsx"
          style="display: inline-block"
        >
          <el-button
            plain
            type="primary"
            v-loading="uploadLoading"
            v-if="
              buttonDisplayOrNot(buttonCodes, 'zzPersonnelImportBtn') &&
              bindType != 2
            "
            >人员导入</el-button
          >
        </el-upload>
      </template>
      <template v-slot:downloadTemp>
        <el-button
          type="primary"
          v-loading="uploadLoading"
          @click="downloadTemp"
          v-if="
            buttonDisplayOrNot(buttonCodes, 'zzImportTemplateBtn') &&
            bindType != 2
          "
          >导入模板下载</el-button
        >
      </template>
    </TableSearch>
    <Table
      ref="tableRef"
      v-bind="state.tableData"
      @listenClick="listenClick"
      @dataList="dataList"
    >
      <template #default="{ slotData, slotColumn }">
        <div v-if="slotColumn.key === 'sex'">
          {{ slotData.sex == 1 ? '男' : slotData.sex == 2 ? '女' : '--' }}
        </div>
        <div v-if="slotColumn.key === 'enableState'">
          <el-switch
            v-model="slotData.enableState"
            :active-value="1"
            :inactive-value="2"
            :disabled="
              !buttonDisplayOrNot(buttonCodes, 'zzEditPersonnelBtn') ||
              slotData.roleId == '2c195fa2612b49f99647e4fe1962319a' ||
              slotData.roleId == 'f65531c3ae374678a67b3bdacafb4537'
            "
            style="
              --el-switch-on-color: var(--el-color-primary);
              --el-switch-off-color: #fa4016;
            "
            @change="(val: any) => {
								changeStatus(val, slotData)
							}
							"
          />
        </div>
      </template>
    </Table>
    <DeptAccountDialog
      :myDialog="accountDia"
      :row="curRow"
      @flash="getTableData"
    ></DeptAccountDialog>
    <DeptPersonDialog
      :myDialog="personDia"
      :row="curRow"
      :curDept="curDept"
      @flash="getTableData"
    ></DeptPersonDialog>
    <TransferAdmin
      :transferDialog="transferDialog"
      @deptSubmit="deptSubmit"
      @toBackDept="toBackDept"
    ></TransferAdmin>
    <el-dialog
      v-model="resetDialog"
      title="重置密码"
      width="30%"
      :show-close="false"
    >
      <span>是否重置密码？默认密码为：Admin@123</span
      ><span class="copyPwd" @click="copyPwd">复制密码</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetDialog = false">取消</el-button>
          <el-button type="primary" @click="czPwd"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  onMounted,
  onBeforeUnmount,
  defineAsyncComponent,
  getCurrentInstance
} from 'vue'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import type { UploadProps, UploadUserFile } from 'element-plus'
import emitter from '/@/utils/mitt'
import { exportExcel } from '/@/utils/toolsValidate'
import {
  getRoleList,
  putEnableState,
  putResetPwd,
  deleteUser,
  downloadMould,
  importUser,
  transferAdministratorApi
} from '/@/api/setting/structure'
import { Session } from '/@/utils/storage'
import router from '/@/router'
import { buttonDisplayOrNot } from '../../../utils/buttonBoolean'
import { getButtonListByRoleApi } from '/@/api/publicApi'
const menu = Session.get('menu')

const buttonCodes = ref<any>([])
const token = JSON.parse(sessionStorage.getItem('shebei') as any).token
const roleId = JSON.parse(sessionStorage.getItem('shebei') as any).roleId
const bindType = JSON.parse(sessionStorage.getItem('shebei') as any).bindType
const headers = {
  'Content-Type': 'multipart/form-data',
  'API-User-Token': token
}
const { proxy } = getCurrentInstance() as any
const Table = defineAsyncComponent(
  () => import('/@/components/table/index.vue')
)
const TableSearch = defineAsyncComponent(
  () => import('/@/components/table/search.vue')
)
const DeptAccountDialog = defineAsyncComponent(
  () => import('/@/views/setting/components/DeptAccountDialog.vue')
)
const DeptPersonDialog = defineAsyncComponent(
  () => import('/@/views/setting/components/DeptPersonDialog.vue')
)
const TransferAdmin = defineAsyncComponent(
  () => import('/@/views/setting/components/TransferAdmin.vue')
)
// 表格
const tableRef = ref<RefType>()
const state = reactive<TableDemoState>({
  tableData: {
    flash: false, // 刷新表格
    // 表头内容（必传，注意格式）
    header: [
      { key: 'realName', colWidth: '', title: '姓名', type: 'text' },
      {
        key: 'userAccount',
        colWidth: '',
        title: '账号',
        type: 'text',
        hide: bindType != 1
      },
      {
        key: 'userTel',
        colWidth: '',
        title: '手机号',
        type: 'text',
        hide: bindType != 2
      },
      { key: 'sex', colWidth: '60', title: '性别', type: 'slot' },
      { key: 'deptName', colWidth: '', title: '部门机构', type: 'text' },
      { key: 'roleName', colWidth: '', title: '角色类型', type: 'text' },
      { key: 'positionName', colWidth: '', title: '职位', type: 'text' },
      { key: 'enableState', colWidth: '', title: '账号状态', type: 'slot' },
      { key: 'entryDate', colWidth: '', title: '入职时间', type: 'text' }
    ],
    columnBtn: [
      {
        // 操作按钮
        name: 'edit',
        text: '编辑',
        color: '#1962E0',
        hide(row: any): boolean {
          return true
        },
        btns: buttonCodes.value,
        btnCode: 'zzEditPersonnelBtn'
      },
      {
        name: 'changeAccount',
        text: '更换账号',
        type: 'primary',
        hide(row: any): boolean {
          return bindType == 1 || bindType == ''
        },
        btns: buttonCodes.value,
        btnCode: 'zzChangeAccountBtn'
      },
      {
        name: 'reset',
        text: '重置密码',
        color: '#FC770A',
        hide(row: any): boolean {
          return bindType == 1 || bindType == ''
        },
        btns: buttonCodes.value,
        btnCode: 'zzResetPasswordBtn'
      },
      {
        name: 'deleteItem',
        text: '删除',
        color: '#FA4016',
        hide(row: any): boolean {
          return bindType == 1 || bindType == ''
        },
        btns: buttonCodes.value,
        btnCode: 'zzDeleteBtn'
      },
      {
        name: 'transfer',
        text: '管理员移交',
        type: 'primary',
        hide(row: any): boolean {
          return (
            (row.roleId == '2c195fa2612b49f99647e4fe1962319a' ||
              row.roleId == 'f65531c3ae374678a67b3bdacafb4537') &&
            roleId == row.roleId
          )
        },
        btns: buttonCodes.value,
        btnCode: 'zzTransferBtn'
      }
    ],
    // 配置项（必传）
    config: {
      listApi: '/user/mobile/userInfo/userList', // 请求接口
      listHttp: 'post', // 请求方式
      total: 0, // 列表总数
      loading: true, // loading 加载
      noPage: false, // 是否分页 false分页，true不分
      isSerialNo: true, // 是否显示表格序号
      isSelection: false, // 是否显示表格多选
      isOperate: true, // 是否显示表格操作栏
      isExtend: false // 是否可以扩展
    },
    // 搜索参数
    param: {
      deptId: '' // 必传参数，分页的不要传
    },
    extendTable: {
      // 二级表格
    }
  },
  // 搜索表单，动态生成（传空数组时，将不显示搜索，注意格式）
  search: {
    param: [
      {
        label: '',
        prop: 'keyword',
        placeholder: '可输入账号、姓名搜索',
        type: 'input'
      },
      {
        label: '角色类型',
        prop: 'roleId',
        placeholder: '角色类型',
        options: [],
        type: 'select'
      }
      // { label: '时间', prop: 'time', placeholder: '请选择', type: 'daterange', propstart:'start',propsend:'end'},
    ],
    btn: [
      {
        text: 'addPerson',
        fun: 'addPerson',
        disable: false,
        loading: false,
        type: 'slot'
      },
      {
        text: 'importTemp',
        fun: 'importTemp',
        disable: false,
        loading: false,
        type: 'slot'
      },
      {
        text: 'downloadTemp',
        fun: 'downloadTemp',
        disable: false,
        loading: false,
        type: 'slot'
      }
    ],
    reset: true
  }
})

// 获取角色（下拉搜索）
const getRoles = async () => {
  let res = await getRoleList()
  if (res.code == 0) {
    res.data.forEach((element: any) => {
      let p = {
        configValue: element.roleName,
        id: element.id
      }
      state.search.param[1].options.push(p)
    })
    state.search.param[1].options.unshift({
      configValue: '全部',
      id: ''
    })
  }
}

// 获取当前点击的树节点
const deptId = ref('')
emitter.on('deptCurrentNode', (node: any) => {
  state.tableData.param.deptId = node.id
  deptId.value = node.id
  getTableData()
})

onMounted(() => {
  getRoles()
  menu.forEach(async (element: any) => {
    if (element.menuUrl == '/setting/Structure') {
      let res = await getButtonListByRoleApi({
        terminalType: 1,
        menuPid: element.id
      })
      res.data.forEach((item: any) => {
        buttonCodes.value.push(item.buttonCode)
      })
    }
  })
})
// 表格刷新
const getTableData = () => {
  state.tableData.flash = !state.tableData.flash
}
// 账号dialog，当前行，新增人dialog
let [accountDia, curRow, personDia, curDept] = [
  ref<boolean>(false),
  ref({}),
  ref<boolean>(false),
  ref('')
]
// 添加人
const addPerson = () => {
  curRow.value = {}
  curDept.value = deptId.value
  personDia.value = !personDia.value
}

// 下载模板
let timer: any = null
const downloadTemp = () => {
  timer && clearTimeout(timer)
  timer = setTimeout(async () => {
    let res = await downloadMould()
    exportExcel('人员导入模板', res)
  }, 1000)
}

// 搜索点击时表单回调
const onSearch = (data: EmptyObjectType) => {
  state.tableData.param = Object.assign({}, state.tableData.param, { ...data })
  // console.log(state.tableData.param);

  state.tableData.flash = !state.tableData.flash
}
// 修改状态
const user = Session.get('shebei')

const changeStatus = async (val: any, row: any) => {
  if (row.id) {
    let res = await putEnableState({ userId: row.id, enableState: val })
    if (res.code == 0) {
      ElMessage.success('修改成功！')
      if (user.userId == row.id && val == 2) {
        router.replace({
          name: 'login',
          // 登录成功后跳入浏览的当前页面
          query: { redirect: router.currentRoute.value.fullPath }
        })
      }
    } else {
      getTableData()
    }
  }
}

// 编辑
const edit = (row: any) => {
  curRow.value = JSON.parse(JSON.stringify(row))
  personDia.value = !personDia.value
}
// 修改账号
const changeAccount = (row: any) => {
  curRow.value = JSON.parse(JSON.stringify(row))
  accountDia.value = !accountDia.value
}
// 重置密码
const resetDialog = ref(false)
const resetId = ref('')
const reset = (row: any) => {
  resetId.value = row.id
  resetDialog.value = !resetDialog.value
}

const czPwd = async () => {
  let res = await putResetPwd({ userId: resetId.value })
  if (res.code == 0) {
    ElMessage.success('已重置密码！')
    resetDialog.value = !resetDialog.value
    getTableData()
  }
}

const copyPwd = async () => {
  navigator.clipboard.writeText('Admin@123').then(function () {
    ElMessage.success('复制成功！')
  })
}

// 删除
const deleteItem = (row: any) => {
  ElMessageBox.confirm('确定删除该用户？', '删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      let res = await deleteUser({ userId: row.id })
      if (res.code == 0) {
        ElMessage({
          type: 'success',
          message: '已删除'
        })
        // getTableData()
        state.tableData.flash = !state.tableData.flash
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消'
      })
    })
}

/**
 * 人员导入
 */
const fileList = ref<UploadUserFile[]>([])
const uploadLoading = ref<boolean>(false)

const fileBeforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  // console.log('rawFile', rawFile)
  uploadLoading.value = true
}

// 上传成功，发送文件消息
const handleUpload = async (file: any) => {
  importUser({ file: file.file }).then((res) => {
    if (res.code == 0) {
      uploadLoading.value = false
      fileList.value = []
      ElNotification({
        title: '人员导入成功',
        message: '',
        type: 'success'
      })
      getTableData()
    } else {
      // ElMessage.error('文件解析失败，请检查是否符合导入模板规则')
      uploadLoading.value = false
      fileList.value = []
    }
  })
}
const fileError = () => {
  ElMessage.error('文件上传失败！')
  fileList.value = []
  uploadLoading.value = false
}

onBeforeUnmount(() => {
  emitter.off('deptCurrentNode')
})

const dataList = (list: any) => {
  emitter.emit('tableListNum', list.records.length)
}

//管理员移交
const transferDialog = ref(false)
const transferId = ref(false)
const transfer = (row: any) => {
  transferId.value = row.id
  transferDialog.value = true
}

const toBackDept = () => {
  transferDialog.value = false
}

const deptSubmit = async (val: any) => {
  let res = await transferAdministratorApi(transferId.value, val.id)
  if (res.code == 0) {
    ElMessage.success('移交成功')
    getTableData()
  }
}

//定义方法对象 注意定义的方法 必须在上面已经申明 所以建议objFun申明和 listenClick方法 写在页面最下面
const objFun = {
  addPerson: addPerson,
  downloadTemp: downloadTemp,
  edit: edit,
  changeAccount: changeAccount,
  reset: reset,
  deleteItem: deleteItem,
  transfer: transfer
}
// 监听子级表格  传过来的方法
const listenClick = (name: string, val: any) => {
  objFun[name](val)
}
</script>

<style lang="scss" scoped>
.copyPwd {
  margin-left: 5px;
  cursor: pointer;
  text-decoration: underline;
  color: var(--el-color-primary);
}
</style>
<style>
.el-button--primary.is-plain {
  --el-button-bg-color: #ffffff;
  --el-button-hover-text-color: var(--el-color-primary);
  --el-button-hover-bg-color: #ffffff;
}

.el-button--primary.is-plain:hover {
  --el-button-hover-text-color: #fff;
  --el-button-hover-bg-color: var(--el-color-primary);
}
</style>
